package com.heima.wemedia.filter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(value = "wmTokenFilter",urlPatterns = "/*")
@Component
public class WmTokenFilter extends GenericFilterBean {
    /**
     *
     * @param servletRequest  请求
     * @param servletResponse 响应
     * @param filterChain 链
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.获取请求对象
        HttpServletRequest request=   (HttpServletRequest)servletRequest;
        //2.查看请求头是否有userId
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)){
            //2.1 如果有 九丰装一个user信息 存入到 threadLocal 变量中
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtils.setUser(wmUser);
        }

        //3.获取请求对象
        filterChain.doFilter(servletRequest,servletResponse);
        //4.获取请求对象
        WmThreadLocalUtils.clear();//清空登录用户

    }
}
